<?php
namespace Ayhome\Suite\Process;

use think\facade\Config;
use think\Db;


use FastD\Swoole\Process;
use swoole_process;
class Crontab extends Process
{
  public $config = [];
  public function handle(swoole_process $swoole_process)
  {

    // $pidFile = $this->config['pid_file'];
    $crontExpre = new \Ayhome\Suite\Parser\Crontab();

    swoole_timer_tick(1000, function ($id) use($crontExpre) {
      $tasks = $this->config['tasks'];
      foreach ($tasks as $k) {
        if (!$k['cron']) continue;
        $sec = date('s');

        $r = $crontExpre::parse($k['cron']);
        if (!isset($r[$sec])) continue;

        $this->run($k);

        if ($this->config['database']) {
          $u['utime'] = time();
          Db::name($this->config['database'])
                    ->where('id',$k['id'])
                    ->update($u);
        }

      }
    });

    swoole_timer_tick(30000, function ($id) {
      $this->reBuildTask();
    });
  }

  public function run($cron)
  {
    // print_r($cron);
    if ($cron['type'] == 'remote' && $cron['url']) {
      $uri = parse_url($cron['url']);
      $host = $uri['host'];
      $path = $uri['path'];

      $client = new \GuzzleHttp\Client();
      $res = $client->request('GET', $cron['url']);
    }elseif ($cron['type'] == 'class') {
      $cls_arr = explode("/", $cron['url']);
      if (count($cls_arr) == 4) {
        $ac = $cls_arr[3];
        $event = \think\facade\App::controller($cls_arr[0].'/'.$cls_arr[2], $cls_arr[1]);
        $event->$ac();
      }
    }

    
  }

  public function reBuildTask()
  {
    if ($this->config['database']) {
      $tasks = Db::name($this->config['database'])->select();
      $this->config['tasks'] = $tasks;
    }
    if (cache('crontab:run')) {
      $v = cache('crontab:run');
      cache('crontab:run',null);
      $this->run($v);
    }

  }

  public function write($txt = '')
  {
    echo $txt.PHP_EOL;
  }
}
